$(function(){
	new Slideshow($('#slideshow ul'));
});

String.prototype.trim = function() {
	return this.replace(/^[\s\r\n\t]+|[\s\r\n\t]+$/ig, '');
}

var ssTimeout;

function Slideshow(ul) {
	this.speed   = 500;
	this.timeout = 5000;
	
	this.ul 	= ul;
	this.items	= [];
	
	this.screen  = $('<div class="ss-screen">');
	this.btnPrev = $('<a href="javascript:void(0)" class="ss-btn prev"></a>').appendTo(this.screen);
	this.reel    = $('<ul class="ss-reel">').appendTo(this.screen);
	this.btnNext = $('<a href="javascript:void(0)" class="ss-btn next"></a>').appendTo(this.screen);
	
	this.position = 0;
	
	this.switch = function(position, after) {
		if (position<0) {
			position = this.items.length - 1
		} else if(position == this.items.length) {
			position = 0;
		}
	
		this.position = position;
		_this = this;
		
		var lis = this.reel.children('li');
		lis.fadeOut(this.speed, function(){
			lis.eq(_this.position).fadeIn(_this.speed);
		});
	}
	
	this.draw = function() {
		this.ul.after(this.screen);
		
		var item, li, img, box, title, blurb;
		for (var i=0; i<this.items.length; i++) {
			item = this.items[i];
			
			li = $('<li>').appendTo(this.reel);
			
			img = item.image.clone();
			img
				.attr('align', 'left')
				.appendTo(li);
			
			box = $('<div class="ss-box">').appendTo(li);
			
			title = $('<h1>');
			title
				.text(item.title)
				.appendTo(box)
				
			box.append(item.blurb);
			
		}
	};
	
	this.loadItems = function() {
		var lis = this.ul.children('li');
		for (var i=0; i<lis.length; i++) {
			this.items.push({
				title: $(lis[i]).children('h1').text(),
				image: $(lis[i]).children('img'),
				blurb: $(lis[i]).children('.blurb').html().trim()
			});
		};
		this.ul.hide();
	};
	
	this.init = function() {
		this.loadItems();
		this.draw();
		
		var _this=this;
		this.screen.mouseover(function(){
			if (_this.items.length > 1) {
				_this.btnPrev.show();
				_this.btnNext.show();
			}
		});
		this.screen.mouseout(function(){
			if (_this.items.length > 1) {
				_this.btnPrev.hide();
				_this.btnNext.hide();
			}
		});
		this.btnNext.click(function(){
			if (ssTimeout) {
				clearTimeout(ssTimeout);
			}
			_this.play(_this.position + 1);
		});
		this.btnPrev.click(function(){
			if (ssTimeout) {
				clearTimeout(ssTimeout);
			}
			_this.play(_this.position - 1);
		});
	};
	
	this.play = function(pos) {
		pos = typeof(pos)!='undefined' ? pos : this.position;
		_this=this;
		_this.switch(pos);
		ssTimeout = setTimeout(function(){
			_this.play(_this.position+1);
		}, _this.timeout);
	}
	
	
	this.init();
	if (this.items.length > 1) {
		this.play();
	} else {
		this.switch(0);
	}
}